package com.res.share.controller;

import com.res.share.common.Constants;
import com.res.share.common.WebResponse;
import com.res.share.common.utils.FileUtils;
import com.res.share.model.ResArt;
import com.res.share.model.ResMessage;
import com.res.share.model.ResUser;
import com.res.share.model.dto.UserStatisModel;
import com.res.share.service.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger("UserController");

    @Autowired
    private IResCollectionService resCollectionService;

    @Autowired
    private IResHistoryService resHistoryService;

    @Autowired
    private IResUserService resUserService;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private IResArtService resArtService;

    @Autowired
    private IResFollowService resFollowService;

    @Autowired
    private ImageService imageService;


    @Autowired
    private IResDownService resDownService;

    @Autowired
    private IResStatisticsService resStatisticsService;

    private static final Lock lock = new ReentrantLock();

    /**
     * 更新收藏
     *
     * @param articleId
     * @return
     */
    @PostMapping("/updateCollection.html")
    @ResponseBody
    public WebResponse updateArticleCollectionStatus(HttpServletRequest request, @RequestParam("articleId") Integer articleId) {
        Integer result = null;
        try {
            Integer userId = null;
            Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
            if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
                userId = Integer.valueOf(attribute.toString());
            } else {
                return WebResponse.ok(-1);
            }
            result = resCollectionService.updateArticleCollectionStatus(articleId, userId);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResponse.error(-2);
        }
        return WebResponse.ok(result);
    }


    /**
     * 取消收藏
     *
     * @param collectionId
     * @return
     */
    @PostMapping("/delcollectionArticle.html")
    @ResponseBody
    public WebResponse delcollectionArticle(HttpServletRequest request, @RequestParam("collectionId") String collectionId) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        } else {
            return WebResponse.ok(-1);
        }
        List<String> collect = Arrays.stream(collectionId.split(",")).distinct().collect(Collectors.toList());
        resCollectionService.updateBatchDelcollectionArticle(collect, userId);
        return WebResponse.ok(1);
    }


    /**
     * 删除历史
     *
     * @param historyId
     * @return
     */
    @PostMapping("/delHistory.html")
    @ResponseBody
    public WebResponse delHistory(HttpServletRequest request, @RequestParam("historyId") String historyId) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        if (userId == null) {
            return WebResponse.ok(-1);
        }
        List<String> collect = Arrays.stream(historyId.split(",")).distinct().collect(Collectors.toList());
        resHistoryService.updateBatchDelHistory(collect, userId);
        return WebResponse.ok(1);
    }


    /**
     * 修改密码
     *
     * @param
     * @return
     */
    @PostMapping("/editUserDetail.html")
    @ResponseBody
    public WebResponse editUserDetail(HttpServletRequest request, @RequestParam("password") String password) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        if (userId == null) {
            return WebResponse.ok(-1);
        }
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        resUserService.updateUserPassword(md5Password, userId);
        cacheService.deleteCache(Constants.CURRENT_USER_DETAIL + userId);
        return WebResponse.ok(1);
    }

    /**
     * 修改密码
     *
     * @param
     * @return
     */
    @PostMapping("/updateUserImage.html")
    @ResponseBody
    public WebResponse updateUserImage(HttpServletRequest request, @RequestParam("userImage") String userImage) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        if (userId == null) {
            return WebResponse.ok(-1);
        }
        resUserService.updateUserImage(userImage, userId);
        cacheService.deleteCache(Constants.CURRENT_USER_DETAIL + userId);
        cacheService.deleteCache(Constants.RES_NEW_ARTICLE_KEY);
        cacheService.deleteCache(Constants.RES_ARTICLE_BASE_KEY);
        cacheService.deleteCache(Constants.HOT_ARTICLE_BASE_KEY);
        return WebResponse.ok(1);
    }


    /**
     * 绑定邮箱
     *
     * @param request
     * @param emailCode
     * @param userEmail
     * @return
     */
    @PostMapping("/bindEmail.html")
    @ResponseBody
    public WebResponse bindEmail(HttpServletRequest request,
                                 @RequestParam("emailCode") String emailCode,
                                 @RequestParam("userEmail") String userEmail) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        if (userId == null) {
            return WebResponse.ok(-1);
        }
        boolean email = false;
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equalsIgnoreCase(Constants.EMIAL_CODE) && cookie.getValue().equalsIgnoreCase(emailCode)) {
                    email = true;
                    break;
                }
            }
        }
        if (!email) {
            //邮箱验证码失效
            return WebResponse.ok(-1);
        }
        //邮箱已被注册过
        ResUser resUser = resUserService.checkUserExits(userEmail, 1);
        if (resUser != null) {
            return WebResponse.ok(-2);
        }
        resUserService.updateUserEmail(userId, userEmail);
        cacheService.deleteCache(Constants.CURRENT_USER_DETAIL + userId);
        return WebResponse.ok(1);
    }


    /**
     * 签到
     *
     * @param request
     * @return
     */
    @GetMapping("/sign.html")
    @ResponseBody
    public WebResponse userSign(HttpServletRequest request) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        } else {
            return WebResponse.ok(-1);
        }
        Integer result = resUserService.userSign(userId);
        return WebResponse.ok(result);
    }

    /**
     * 下载数据
     *
     * @param request
     * @param articleId
     * @return
     */
    @PostMapping("/uploadResData.html")
    @ResponseBody
    public WebResponse uploadResData(HttpServletRequest request, @RequestParam("articleId") Integer articleId) {
        log.info("获取下载链接,articleId:[{}]", articleId);
        Integer userId = null;
        String artUploadModel = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        } else {
            return WebResponse.ok(-1);
        }
        log.info("获取下载链接获取锁,articleId:[{}]", articleId);
        try {
            lock.lock();
            ResArt resArt = resArtService.findArtDataById(articleId);
            //判断用户是否下载过
            boolean articleUpload = resDownService.checkArticleUpload(userId, articleId);
            if (articleUpload) {
                artUploadModel = resArtService.findArtUploadData(userId, articleId, resArt.getFreeType());
            } else {
                Integer money = resArt.getMoney();
                if (resArt.getFreeType() == 1) {
                    //查询是否开通了会员
                    ResUser currentUserInfo = resUserService.findCurrentUserInfo(userId);
                    Integer userType = currentUserInfo.getUserType();
                    if (userType == 0) {
                        //未开通会员 判断是否存在足够的资源币
                        UserStatisModel userStatisModel = resStatisticsService.findPersionDetail(userId);
                        Integer resNum = userStatisModel.getResNum();
                        if (resNum > 0) {
                            int countNum = resNum.intValue() - money.intValue();
                            if (countNum >= 0) {
                                artUploadModel = resArtService.findArtUploadData(userId, articleId, resArt.getFreeType());
                                if (StringUtils.isNotEmpty(artUploadModel)) {
                                    resStatisticsService.updateUserResNum(userId, countNum);
                                }
                            } else {
                                return WebResponse.ok(-3);
                            }
                        } else {
                            artUploadModel = resArtService.findArtUploadData(userId, articleId, resArt.getFreeType());
                        }
                    } else {
                        return WebResponse.ok(-2);
                    }
                } else {
                    artUploadModel = resArtService.findArtUploadData(userId, articleId, resArt.getFreeType());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取下载链接发生异常,articleId:[{}],e:[{}]", articleId, e);
        } finally {
            lock.unlock();
            log.info("获取下载链接释放锁,articleId:[{}]", articleId);
        }
        return WebResponse.ok(artUploadModel);
    }


    /**
     * 关注
     *
     * @param request
     * @param followMeBelongId
     * @param type             1- 关注 0- 为关注
     * @return
     */
    @PostMapping("/editFollowMe.html")
    @ResponseBody
    public WebResponse editFollowMe(HttpServletRequest request,
                                    @RequestParam("followMeBelongId") Integer followMeBelongId,
                                    @RequestParam("type") Integer type) {
        Integer result = null;
        try {
            Integer userId = null;
            Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
            if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
                userId = Integer.valueOf(attribute.toString());
            } else {
                return WebResponse.ok(-1);
            }
            result = resFollowService.editFollowMe(userId, followMeBelongId, type);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResponse.error(-2);
        }
        return WebResponse.ok(result);
    }

    /**
     * 取消关注
     *
     * @param request
     * @param followUserId
     * @return
     */
    @PostMapping("/cancelLikeUser.html")
    @ResponseBody
    public WebResponse cancelLikeUser(HttpServletRequest request, @RequestParam("followUserId") String followUserId) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        } else {
            return WebResponse.ok(-1);
        }
        resFollowService.cancelLikeUser(followUserId, userId);
        return WebResponse.ok(1);
    }

    /**
     * 图片上传，需要赋值读写权限-->
     *
     * @param request
     * @return
     * @author wangsong
     * @date 2019年6月14日 下午2:31:49
     */
    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public WebResponse uploadImage(MultipartFile file, HttpServletRequest request) {

        String fileUrl = null;
        try {
            Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
            if (attribute == null || StringUtils.isEmpty(attribute.toString())) {
                return WebResponse.ok(-1);
            }
            String fileName = file.getOriginalFilename();
            String fileSuffix = FileUtils.getFileSuffix(fileName);
            long fileSize = file.getSize() / 1024;
            if (fileSize > 2000 * 1024) { //判断图片大小 单位Kb
                return WebResponse.ok(-2, "请上传小于或等于2M的图片");
            }
            if (StringUtils.isBlank(fileSuffix) ||
                    (!fileSuffix.equalsIgnoreCase(".png") &&
                            !fileSuffix.equalsIgnoreCase(".jpg"))) { //如果image=null 表示上传的不是图片格式
                return WebResponse.ok(-3, "图片格式不正确");
            }
            fileUrl = imageService.uploadImage(file, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WebResponse.ok(fileUrl);
    }


    /**
     * 发送消息
     *
     * @param request
     * @param receiveName
     * @param content
     * @param title
     * @return
     */
    @PostMapping("/sendMessageToReceiveId")
    @ResponseBody
    public WebResponse sendMessageToReceiveId(HttpServletRequest request,
                                              @RequestParam("receiveName") String receiveName,
                                              @RequestParam("content") String content,
                                              @RequestParam("title") String title) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        } else {
            return WebResponse.ok(-1);
        }
        //判断结束人是否存在
        ResUser userDetail = resUserService.findUserDetail(receiveName);
        if (userDetail == null) {
            return WebResponse.ok(-2);
        }
        resUserService.addMessage(userId, userDetail.getId(), content, title, 3);
        return WebResponse.ok(1);
    }


    /**
     * 读取数据
     *
     * @param request
     * @return
     */
    @PostMapping("/findMessageByNotifyId")
    @ResponseBody
    public WebResponse findMessageByNotifyId(HttpServletRequest request, @RequestParam("id") Integer id, @RequestParam("type") Integer type) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        } else {
            return WebResponse.ok(-1);
        }
        ResMessage resMessage = resUserService.findMessageByNotifyId(id, type, userId);
        return WebResponse.ok(resMessage);
    }


    /**
     * 删除
     *
     * @param request
     * @param messageIds
     * @param type
     * @return
     */
    @PostMapping("/delMessageNotify.html")
    @ResponseBody
    public WebResponse delMessageNotify(HttpServletRequest request, @RequestParam("messageIds") String messageIds, @RequestParam("type") Integer type) {
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        } else {
            return WebResponse.ok(-1);
        }
        List<String> collect = Arrays.stream(messageIds.split(",")).distinct().collect(Collectors.toList());
        resUserService.delMessageNotify(collect, userId, type);
        return WebResponse.ok(1);
    }

}

